package org.wzy.xmlg_backend.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jakarta.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Configuration
public class FileStorageConfig implements WebMvcConfigurer {

    @Value("${file.upload-dir:D:/upload/}")
    private String uploadDir;

    @Value("${file.access-path:/uploads/}")
    private String accessPath;

    @PostConstruct
    public void init() {
        try {
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
                System.out.println("创建上传目录: " + uploadPath.toAbsolutePath());
            }
        } catch (IOException e) {
            System.err.println("无法创建上传目录: " + e.getMessage());
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 确保路径以斜杠结尾
        String handlerPath = accessPath.endsWith("/") ? accessPath : accessPath + "/";
        String location = "file:" + (uploadDir.endsWith("/") ? uploadDir : uploadDir + "/");

        registry.addResourceHandler(handlerPath + "**")
                .addResourceLocations(location);

        System.out.println("配置静态资源映射: " + handlerPath + "** -> " + location);
    }
}